const {Role, Menu, RolePermission, Op} = require("../db/seq");

class RoleServe {
    async getRoleListServe(ctx) {
        const {pageSize = 10, pageNum = 1, jobTitle} = ctx.request.query;
        const whereOptArr = []
        const whereOpt = {}
        jobTitle && Object.assign(whereOpt, {
            jobTitle: {
                // 模糊查询
                [Op.like]: '%' + jobTitle.trim() + '%'
            }
        });
        whereOptArr.push(whereOpt)
        const offset = (pageNum - 1) * pageSize;
        const {count, rows} = await Role.findAndCountAll({
            attributes: {exclude: ['deletedTime', 'createdByUserId']},
            where: whereOptArr.length > 1 ? {
                [Op.and]: [
                    ...whereOptArr
                ]
            } : whereOpt,
            //分页
            offset,
            //限制
            limit: Number(pageSize)
        })
        return {
            total: count,
            data: rows,
            pageNum,
            pageSize
        }
    }

    async addRoleServe(jobTitle, createdByUserId) {
        const res = await Role.create({jobTitle, createdByUserId})
        return res.dataValues
    }

    async getRoleById(roleId) {
        let res;
        if (roleId.length > 1) {
            res = await Role.findAll({
                where: {
                    id: {
                        [Op.or]: roleId.split(',')
                    }
                },
                include: {
                    model: Menu
                }
            })
        } else {
            res = await Role.findOne({
                where: {
                    id: roleId
                },
                include: {
                    model: Menu
                }
            })
        }
        return res
    }


    async getRoleByJobTitle(JobTitle) {
        const res = await Role.findOne({
            where: {
                JobTitle
            }
        })
        return res ? res.dataValues : null;
    }

    async updateRoleServe(jobTitle, roleId) {
        const res = await Role.update({jobTitle}, {
            where: {
                id: roleId
            }
        })
        return res[0] > 0;
    }

    async deleteRoleServe(id) {
        const res = await Role.destroy({
            where: {
                id
            }
        })
        return res > 0
    }

    async getRoleServe() {
        const res = await Role.findAll({
            attributes: {exclude: ['deletedTime', 'createdByUserId']},
        });
        return res ? res : null;
    }

    async getCurrentUserRoleInfoServe(roleId) {

        const res = await Role.findAll({
            where: {
                id: roleId
            },
            include: {
                model: RolePermission
            }
        })
        return res ? res : null;
    }
}

module.exports = new RoleServe();
